package com.desgin.pattern.commmand;

/**
 * @author SaErNuoSi
 * @date 2018/4/26 15:19
 */
public class RemoteController {
    Command[] onCommands;
    Command[] offCommands;
    Command cancelCommand;
    int length;

    public RemoteController(int length) {
        this.length = length;
        onCommands = new Command[length];
        offCommands = new Command[length];
        /*定义一个没有任何操作的命令,否则代码里面会有各种空判断*/
        Command noCommand = new NoCommand();
        for (int i = 0; i < length; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        /*初始化的时候没有一个可以撤销的指令,所以用没有指令这个对象来替代*/
        cancelCommand = noCommand;
    }

    /**
     * 设置命令的执行顺序
     *
     * @param position
     * @param onCommand
     * @param offCommand
     */
    public void setCommand(int position, Command onCommand, Command offCommand) {
        onCommands[position] = onCommand;
        offCommands[position] = offCommand;
    }

    public void pushON(int position) {
        onCommands[position].execute();
        cancelCommand = onCommands[position];
    }

    public void pushOFF(int position) {
        offCommands[position].execute();
        cancelCommand = offCommands[position];
    }

    /**
     * 撤销上一次操作
     */
    public void cancelCommand() {
        cancelCommand.undo();
    }
}
